package com.lucher.mes.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lucher.mes.common.Tools;
import com.lucher.mes.common.Uuid;
import com.lucher.mes.dao.ProblemMapper;
import com.lucher.mes.dao.ProductMapper;
import com.lucher.mes.dao.ProductworkorderMapper;
import com.lucher.mes.dao.WorkorderMapper;
import com.lucher.mes.dao.WorkorderproblemMapper;
import com.lucher.mes.po.Problem;
import com.lucher.mes.po.Product;
import com.lucher.mes.po.Productworkorder;
import com.lucher.mes.po.Workorder;
import com.lucher.mes.po.Workorderproblem;
import com.lucher.mes.service.ISystemparaService;

@Controller
@RequestMapping("/workorder")  
public class WorkorderController extends BaseController{
	@Autowired
	private WorkorderMapper workorderDao;
	@Autowired
	private ProblemMapper problemDao;
	@Autowired
	private WorkorderproblemMapper workorderproblemDao;
	@Autowired
	private ISystemparaService systemparaService;
	@Autowired
	private ProductworkorderMapper productworkorderDao;
	@Autowired
	private ProductMapper productDao;
	/**
	 * 查询信息
	 */
	@RequestMapping(value = "/findByList")
	public String findByList(Workorder form) {
		return "workorder/findWorkorderList";
	}
	
	/**
	 * 查询信息Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findListJson")
	public Map<String, Object> findListJson(Workorder form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		result.put("code", "0");
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
		
		Integer total = workorderDao.findByCount(form);
		List<Workorder> list = workorderDao.findByListForPage(form);
		
		for (Workorder workorder : list) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			
			objectMap.put("id", workorder.getId());
			objectMap.put("ordercode", workorder.getOrdercode());
			objectMap.put("ordername", workorder.getOrdername());
			objectMap.put("info", workorder.getInfo());
			objectMap.put("filepath", workorder.getFilepath());
			objectMap.put("remark", workorder.getRemark());
			objectlist.add(objectMap);
		}
		
		result.put("count", total);
		result.put("data", objectlist);
		return result;
	}

	/**
	 * 添加信息初始化
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addInit")
	public String addInit(Workorder form,Model model) {
		//查询所有的问题信息
		List<Problem> problemlist = problemDao.findByList(new Problem());
		model.addAttribute("problemlist", problemlist);
		return "workorder/addWorkorder";
	}

	/**
	 * 新增
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/save")
	@Transactional
	public Map<String,Object>  save(Workorder form) {
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		//系统自动生产工序编号
		form.setOrdercode(Uuid.generateShortUuid());
		
		if ("".equals(form.getOrdercode())) {
			responseJson.put("flag", "0"); //操作失败
			responseJson.put("msg", "操作失败，请输入编号");
			return responseJson;
		} else {
			Workorder oldWorkorder = workorderDao.findByOrdercode(form.getOrdercode());
			if (oldWorkorder != null) {
				responseJson.put("flag", "0");//操作失败
				responseJson.put("msg", "操作失败，此编号已经存在");
				return responseJson;
			}
		}
		
		String problemcodes = form.getProblemcodes();
		if(StringUtils.isBlank(problemcodes)){
			responseJson.put("flag", "0");//操作失败
			responseJson.put("msg", "操作失败，请先选择工序检验问题信息");
			return responseJson;
		}

		//已有的工序数量
		int count = productworkorderDao.findCountByProduct(form.getProductcode());

		if(count>=50){
			responseJson.put("flag", "0");//操作失败
			responseJson.put("msg", "操作失败，最多设置50个工序");
			return responseJson;
		}

		//保存工序
		workorderDao.insertSelective(form);
		
		//添加关联的产品
		if(StringUtils.isNotBlank(form.getProductcode())){
			Product product = productDao.findByProductcode(form.getProductcode());
			if(product != null){
				Productworkorder productworkorder = new Productworkorder();
				productworkorder.setProductcode(form.getProductcode());
				productworkorder.setProductname(product.getProductname());
				productworkorder.setOrdercode(form.getOrdercode());
				productworkorder.setOrdername(form.getOrdername());
				productworkorderDao.insertSelective(productworkorder);
			}
		}
		
		//新添加关联的问题
		String[] problemcodeArr = problemcodes.split(",");
		for (String problemcode : problemcodeArr) {
			Problem problem = problemDao.findByProblemcode(problemcode);
			Workorderproblem workorderproblem = new Workorderproblem();
			workorderproblem.setOrdercode(form.getOrdercode());
			workorderproblem.setOrdername(form.getOrdername());
			workorderproblem.setProblemcode(problemcode);
			workorderproblem.setProblemname(problem.getProblemname());
			workorderproblemDao.insertSelective(workorderproblem);
		}
		
		responseJson.put("flag", "1");//操作成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}

	/**
	 * 更新初始化
	 */
	@RequestMapping(value = "/updateInit")
	public String updateInit(Workorder form,Model model) {
		Workorder workorder = workorderDao.selectByPrimaryKey(form.getId());
		form.setWorkorder(workorder);

		//查询所有已经被选用的
		Workorderproblem record = new Workorderproblem();
		record.setOrdercode(workorder.getOrdercode());
		List<Workorderproblem> workorderproblemList = workorderproblemDao.findByList(record);
		
		//查询所有的工序质检问题信息
		List<Problem> problemlist = problemDao.findByList(new Problem());
		
		//循环所有的工位机信息
		for (Problem problem : problemlist) {
			for (Workorderproblem workorderproblem : workorderproblemList) {
				if(problem.getProblemcode().equals(workorderproblem.getProblemcode())){
					problem.setPageSelected(true);
				}else{
					continue;
				}
			}
		}
		
		model.addAttribute("problemlist", problemlist);
		
		return "workorder/updateWorkorder";
	}

	/**
	 * 更新
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/update")
	@Transactional
	public Map<String,Object> update(Workorder form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		Workorder workorder_old = workorderDao.selectByPrimaryKey(form.getId());
		
		if ("".equals(form.getOrdercode())) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，编号不能为空");
			return responseJson;
		} 
		
		Workorder oldWorkorder = workorderDao.findByOrdercode(form.getOrdercode());
		if (oldWorkorder != null && !oldWorkorder.getId().equals(form.getId())) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，编号已经存在");
			return responseJson;
		}
		

		String problemcodes = form.getProblemcodes();
		if(StringUtils.isBlank(problemcodes)){
			responseJson.put("flag", "0");//操作失败
			responseJson.put("msg", "操作失败，请先选择质检问题信息");
			return responseJson;
		}
		
		// 修改信息
		form.setFilepath(workorder_old.getFilepath());
		workorderDao.updateByPrimaryKeySelective(form);
		
		//修改产品工序信息
		Productworkorder productworkorder = productworkorderDao.selectByPrimaryKey(form.getProductworkorderid());
		if(productworkorder!=null){
			productworkorder.setOrdercode(form.getOrdercode());
			productworkorder.setOrdername(form.getOrdername());
			productworkorderDao.updateByPrimaryKeySelective(productworkorder);
		}
		
		//删除以前的工序
		workorderproblemDao.deleteByOrdercode(workorder_old.getOrdercode());
		
		//新添加关联的工序
		String[] problemcodeArr = problemcodes.split(",");
		for (String problemcode : problemcodeArr) {
			Problem problem = problemDao.findByProblemcode(problemcode);
			Workorderproblem workorderproblem = new Workorderproblem();
			workorderproblem.setOrdercode(form.getOrdercode());
			workorderproblem.setOrdername(form.getOrdername());
			workorderproblem.setProblemcode(problemcode);
			workorderproblem.setProblemname(problem.getProblemname());
			workorderproblemDao.insertSelective(workorderproblem);
		}
		
		responseJson.put("flag", "1");//
		responseJson.put("msg", "操作成功");
		return responseJson;
	}
    
	/**
	 * 删除
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/delete")
	@Transactional
	public Map<String,Object> delete(Workorder form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		Workorder workorder = workorderDao.selectByPrimaryKey(form.getId());
		//删除工序
		workorderDao.deleteByPrimaryKey(form.getId());
		//修改产品工序信息
		productworkorderDao.deleteByPrimaryKey(form.getProductworkorderid());
		//删除工序对应的问题
		workorderproblemDao.deleteByOrdercode(workorder.getOrdercode());
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}
	
	/**
	 * 批量删除
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/deleteBatch")
	public Map<String,Object> deleteBatch(@RequestBody List<Workorder> formlist) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		for (Workorder workorder : formlist) {
			//删除工位机
			workorderDao.deleteByPrimaryKey(workorder.getId());
		}

		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}
	
	
	 /**
      * 上传工序视频文件
      * @param session
      * @param file
      * @param ui
      * @return
      * @throws IOException 
      * @throws IllegalStateException 
      */
     @RequestMapping(value="saveFilepath")
     @ResponseBody //此标志就是返回jesion数据给页面的标志
     public  Map<String,Object> saveFilepath(@RequestParam("file") MultipartFile file,@ModelAttribute Workorder workorder,HttpServletRequest request) throws IllegalStateException, IOException{
         String oldName = file.getOriginalFilename();
         //String path = request.getServletContext().getRealPath("/upload/");
         String upload_file_path = systemparaService.findSystemParaByCodeStr("upload_file_path");
         String folderpath = upload_file_path + File.separatorChar + "workorder";
		 File folder = new File(folderpath);
		 if (!folder.exists()) {
			folder.mkdirs();
		 }
         String fileName = changeName(oldName);
         fileName = folderpath + File.separatorChar + fileName;
         File file1 = new File(fileName);
         file.transferTo(file1);
         
         //System.out.println(ui.getId());
         workorder.setFilepath(fileName);
         workorderDao.updateByPrimaryKeySelective(workorder);
         
         
         //封装返回给页面的json对象
 		HashMap<String,Object> responseJson = new HashMap<String,Object>();
 		responseJson.put("code", "0");
 		responseJson.put("msg", "");
 		HashMap<String,Object> data = new HashMap<String,Object>(); 
 		data.put("src", fileName);
 		responseJson.put("data", data);
        //String str = "{\"code\": 0,\"msg\": \"\",\"data\": {\"src\":\"" + fileName + "\"}}";
         
         return responseJson;
     }
	
     public static String changeName(String oldName){
         Random r = new Random();
         Date d = new Date();
         String newName = oldName.substring(oldName.indexOf('.'));
         newName = r.nextInt(99999999) + d.getTime() + newName;
         return newName;
     }
     
     
     /**
 	 * 查询工序关联检验问题信息Json
 	 */
 	@ResponseBody
 	@RequestMapping(value = "/findProblemListJson")
 	public Map<String, Object> findProblemListJson(Workorderproblem form) {
 		//封装JSon的Map
 		Map<String, Object> result = new HashMap<String, Object>(); 
 		result.put("code", "0");
 		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
 		
 		Integer total = workorderproblemDao.findByCount(form);
 		List<Workorderproblem> list = workorderproblemDao.findByListForPage(form);
 		
 		for (Workorderproblem workorderproblem : list) {
 			HashMap<String, Object> objectMap = new HashMap<String, Object>();
 			
 			objectMap.put("id", workorderproblem.getId());
 			objectMap.put("ordercode", workorderproblem.getOrdercode());
 			objectMap.put("ordername", workorderproblem.getOrdername());
 			objectMap.put("problemcode", workorderproblem.getProblemcode());
 			objectMap.put("problemname", workorderproblem.getProblemname());
 			objectlist.add(objectMap);
 		}
 		
 		result.put("count", total);
 		result.put("data", objectlist);
 		return result;
 	}
}
